<template>
	<view>
		<roc-navbar :title="urlQuery.menuTitle"></roc-navbar>
		<view class="u-p-20">
			<roc-diyform ref="rocDiyform" v-if="Object.keys(urlQuery).length" :modelId="urlQuery.modelId"
				:showFormData="showFormData" :showSubmitBtn="false" @roc-submit="submit"></roc-diyform>
		</view>
		<!-- 子表 -->
		<template v-if="modelDetail.sub_table && modelSubTableDetail.is_list == '1'">
			<view class="sub-table-main">
				<view class="line"></view>
				<view class="title-box u-p-20">
					<view class="sub-table-title">{{ modelSubTableDetail.name }}</view>
					<roc-btn v-if="modelSubTableDetail.is_add == '1'" type="primary" text="添加"
						@click.native="handleSubTableAdd()"></roc-btn>
				</view>
				<!-- 子表内容 -->
				<view class="sub-table-cont u-p-20">
					<template v-if="subTableList.length">
						<uni-swipe-action ref="swipeAction">
							<uni-swipe-action-item :right-options="options" v-for="(row, rowIndex) in subTableList"
								:key="rowIndex" @click="handleSubTableCtrl($event, row, rowIndex)">
								<uni-collapse>
									<uni-collapse-item>
										<template v-slot:title>
											<view class="row-box">
												<view class="text" v-for="item in subTableFieldList.slice(0, 2)"
													:key="item.field">
													<!-- 单元格显示内容处理 -->
													<template v-if="item.type == 'select' || item.type == 'checkbox'">
														<text class="name">{{ item.title }}:</text>
														<text v-for="(vItem, vIndex) in row[item.field].split(',')"
															:key="vIndex" :class="
																keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
															">
															{{ keyValueDatasObj[item.field] && keyValueDatasObj[item.field][vItem] }}
															<text
																v-if="vIndex < row[item.field].split(',').length - 1">,</text>
														</text>
													</template>
													<template v-else-if="item.type == 'radio'">
														<text class="name">{{ item.title }}:</text>
														<text :class="
																keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
															">
															{{ keyValueDatasObj[item.field] && keyValueDatasObj[item.field][row[item.field]] }}
														</text>
													</template>
													<template v-else-if="item.type == 'cascader'">
														<text class="name">{{ item.title }}:</text>
														<text v-for="(vItem, vIndex) in row[item.field].split(',')"
															:key="vIndex" :class="
																keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
															">
															{{ keyValueDatasObj[item.field] && keyValueDatasObj[item.field][vItem] }}
															<text
																v-if="vIndex < row[item.field].split(',').length - 1">/</text>
														</text>
													</template>
													<!-- 千分位 -->
													<template v-else-if="
															item.fieldType == 'int' ||
																(item.type == 'input' && item.props && item.props.type == 'number')
														">
														<text class="name">
															{{ item.title }}
															<text
																v-if="item.children != undefined && item.children[0].children[0] != ''">
																({{ item.children[0].children[0] }})
															</text>
															:
														</text>
														<text>{{ row[item.field] | kgRule }}</text>
													</template>
													<template v-else-if="item.type == 'datePicker'">
														<text class="name">{{ item.title }}:</text>
														<text>{{ row[item.field] == '2000-01-01T00:00:00' ? '' : row[item.field] }}</text>
													</template>
													<template v-else>
														<text class="name">{{ item.title }}:</text>
														<text>{{ row[item.field] }}</text>
													</template>
												</view>
											</view>
										</template>
										<view class="content">
											<view class="text" v-for="item in subTableFieldList.slice(2)"
												:key="item.field">
												<!-- 单元格显示内容处理 -->
												<template v-if="item.type == 'select' || item.type == 'checkbox'">
													<text class="name">{{ item.title }}:</text>
													<text v-for="(vItem, vIndex) in row[item.field].split(',')"
														:key="vIndex" :class="
															keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
														">
														{{ keyValueDatasObj[item.field] && keyValueDatasObj[item.field][vItem] }}
														<text
															v-if="vIndex < row[item.field].split(',').length - 1">,</text>
													</text>
												</template>
												<template v-else-if="item.type == 'radio'">
													<text class="name">{{ item.title }}:</text>
													<text :class="
															keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
														">
														{{ keyValueDatasObj[item.field] && keyValueDatasObj[item.field][row[item.field]] }}
													</text>
												</template>
												<template v-else-if="item.type == 'cascader'">
													<text class="name">{{ item.title }}:</text>
													<text v-for="(vItem, vIndex) in row[item.field].split(',')"
														:key="vIndex" :class="
															keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
														">
														{{ keyValueDatasObj[item.field] && keyValueDatasObj[item.field][vItem] }}
														<text
															v-if="vIndex < row[item.field].split(',').length - 1">/</text>
													</text>
												</template>
												<!-- 千分位 -->
												<template v-else-if="
														item.fieldType == 'int' ||
															(item.type == 'input' && item.props && item.props.type == 'number')
													">
													<text class="name">
														{{ item.title }}
														<text
															v-if="item.children != undefined && item.children[0].children[0] != ''">
															({{ item.children[0].children[0] }})
														</text>
														:
													</text>
													<text>{{ row[item.field] | kgRule }}</text>
												</template>
												<template v-else-if="item.type == 'datePicker'">
													<text class="name">{{ item.title }}:</text>
													<text>{{ row[item.field] == '2000-01-01T00:00:00' ? '' : row[item.field] }}</text>
												</template>
												<template v-else>
													<text class="name">{{ item.title }}:</text>
													<text>{{ row[item.field] }}</text>
												</template>
											</view>
										</view>
									</uni-collapse-item>
								</uni-collapse>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</template>
					<view style="text-align: center;" v-else>
						<image src="@/static/img/nullData.png" style="width: 160rpx;height: 160rpx;"></image>
						<view style="color: #888;">暂无数据~</view>
					</view>
				</view>
			</view>
		</template>
		<view class="u-p-20">
			<u-button type="primary" hover-class="none" :custom-style="{ backgroundColor: '#409eff', color: '#fff' }"
				shape="circle" @click="handleSubmit">
				提交
			</u-button>
		</view>
		<!-- 弹窗相关 -->
		<u-popup :show="subTableFormShow" @close="handleClose" mode="center" :closeable="true" round="20"
			:closeOnClickOverlay="false">
			<view class="popup-main">
				<view class="popup-title">{{ modelSubTableDetail.name }}</view>
				<view class="u-p-20">
					<roc-diyform ref="rocSubTableDiyform" v-if="Object.keys(modelSubTableDetail).length"
						:modelId="modelSubTableDetail.id" :showFormData="subTableShowFormData"
						@roc-submit="subTableSubmit"></roc-diyform>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import valueShowName from '@/mixins/valueShowName.js';
	import {
		getList,
		doAdd,
		doEdit
	} from '@/api/dataAccess.js';
	import {
		doAddSub,
		doEditSub
	} from '@/api/dataSubAccess.js';
	import {
		getModelFieldList,
		getDetail,
		getModelList
	} from '@/api/model.js';
	export default {
		mixins: [valueShowName],
		data() {
			return {
				urlQuery: {},
				// 表单回显数据
				showFormData: {},
				modelDetail: {},
				modelSubTableDetail: {},
				subTableFormShow: false,
				// 子表 表单回显数据
				subTableShowFormData: {},
				// 子表字段
				subTableFieldList: [],
				// 子表内容
				subTableList: [],
				// 子表数据 添加或修改标识
				subTableAddOrEdit: '',
				curEditIndex: 0,
				options: []
			};
		},
		onLoad(option) {
			this.urlQuery = option;
			this.reqDetails().then(() => {
				if (this.urlQuery.rowId) {
					// 编辑回显
					const editRowData = uni.getStorageSync('editRowData');
					this.showFormData = editRowData;
					// 有子表
					if (this.modelDetail.sub_table) {
						this.subTableList = JSON.parse(JSON.stringify(this.showFormData.sub_list));
					}
				}
			});
		},
		methods: {
			// 子表滑动操作（编辑，删除）
			handleSubTableCtrl(e, row, index) {
				// e.index 0编辑  1删除
				if (e.content.text == '编辑') {
					// 子表数据编辑
					this.subTableAddOrEdit = '编辑';
					this.curEditIndex = index;
					this.subTableShowFormData = row;
					this.handleOpen();
				} else {
					// 子表数据删除
					this.subTableList.splice(index, 1);
					this.$refs['swipeAction'].closeAll();
				}
			},
			// 子表添加
			handleSubTableAdd() {
				this.subTableAddOrEdit = '添加';
				this.subTableShowFormData = {};
				this.handleOpen();
			},
			// 子表数据提交
			subTableSubmit(formData) {
				if (this.subTableAddOrEdit == '添加') {
					// 添加
					this.subTableList.unshift(formData);
					console.log("子表数据提交=======>", formData)
					let rocDiyform = this.$refs.rocDiyform
					//过滤出需要计算的字段
					rocDiyform.formRuleJson.forEach(item => {
						if (item.props.subTableCountField) {
							let sum = rocDiyform.form[item.field] ? rocDiyform.form[item.field] : 0
							rocDiyform.form[item.field] = eval(sum + "+" +
								formData[item.props.subTableCountField])
						}
					})

				} else {
					// 修改
					this.subTableList.splice(this.curEditIndex, 1, formData);
				}
				this.handleClose();
			},
			// 请求子表字段
			reqSubTableFieldList(modelId) {
				getModelFieldList({
					model_id: modelId
				}).then(({
					data: {
						data
					}
				}) => {
					if (data != null) {
						this.subTableFieldList = data
							.map(fieldObj => {
								fieldObj.attr_json = JSON.parse(fieldObj.attr_json);
								return fieldObj.attr_json;
							})
							.reverse();
						// 使用mixin方法（获取字段api数据）
						this.getFieldApiData(this.subTableFieldList);
					}
				});
			},
			// 子表form打开
			handleOpen() {
				this.subTableFormShow = true;
			},
			// 子表form关闭
			handleClose() {
				this.subTableFormShow = false;
			},
			// 请求模型详情（是否存在子表）
			async reqDetails() {
				if (this.urlQuery.modelId) {
					// 获取模型详情
					const {
						data: {
							data: detail
						}
					} = await getDetail({
						id: this.urlQuery.modelId
					});
					this.modelDetail = detail;
					
					console.log("模型详情===================>", this.modelDetail)
					console.error("模型详情===================>", JSON.parse(this.modelDetail.completed_json))
					if (this.modelDetail.sub_table) {
						// 获取子表模型详情
						const {
							data: {
								data: modelList
							}
						} = await getModelList();

						this.modelSubTableDetail = modelList.filter(model => {
							return model.code == this.modelDetail.sub_table;
						})[0];
						console.log("子表模型详情==============>", this.modelSubTableDetail)
						// 动态加载 编辑 删除 功能按钮
						if (this.modelSubTableDetail.is_edit == '1') {
							const editOpt = {
								text: '编辑',
								style: {
									backgroundColor: '#007aff'
								}
							};
							this.options.push(editOpt);
						}
						if (this.modelSubTableDetail.is_del == '1') {
							const editOpt = {
								text: '删除',
								style: {
									backgroundColor: '#dd524d'
								}
							};
							this.options.push(editOpt);
						}
						// 请求子表字段
						this.reqSubTableFieldList(this.modelSubTableDetail.id);
					}
				}
			},
			// 提交
			handleSubmit() {
				this.$refs['rocDiyform'].submit();
			},
			async submit(formData) {
				//提交根据模型设置v1,v2字段
				let formRules =  JSON.parse(this.modelDetail.completed_json).formRules;
				formRules.forEach(item =>{
					console.log(item)
					if(item.field.indexOf("_")>-1){
						let vVal =  item.field.split("_");
						console.log(vVal)
						let num =Number(vVal[1].charAt(1))-1
						console.log(num)
						formData[item.field] =formData[vVal[0]]? formData[vVal[0]].split(",")[num]:""
					}
				})
				if (this.urlQuery.rowId) {
					// 编辑
					const rowId = formData.id;
					if (formData.id) delete formData.id;
					if (formData.sub_list) delete formData.sub_list;
					
					if (this.modelDetail.sub_table) {
						// 有子表
						const sendObj = {
							id: rowId,
							code: this.modelDetail.code,
							list: JSON.stringify(formData),
							sub_code: this.modelDetail.sub_table,
							sub_list: JSON.stringify(this.subTableList)
						};
						const {
							data: {
								code,
								msg
							}
						} = await doEditSub(sendObj);
						this.$u.toast(msg);
						if (code != 1) return;
					} else {
						// 无子表
						const sendObj = {
							id: rowId,
							code: this.urlQuery.code,
							list: JSON.stringify(formData)
						};
						const {
							data: {
								code,
								msg
							}
						} = await doEdit(sendObj);
						this.$u.toast(msg);
						if (code != 1) return;
					}
					uni.removeStorageSync('editRowData');
				} else {
					// 添加
					if (this.modelDetail.sub_table) {
						// 有子表
						const sendObj = {
							code: this.modelDetail.code,
							list: JSON.stringify(formData),
							sub_code: this.modelDetail.sub_table,
							sub_list: JSON.stringify(this.subTableList)
						};
						const {
							data: {
								code,
								msg
							}
						} = await doAddSub(sendObj);
						this.$u.toast(msg);
						if (code != 1) return;
					} else {
						// 无子表
						const sendObj = {
							code: this.urlQuery.code,
							list: JSON.stringify(formData)
						};
						const {
							data: {
								code,
								msg
							}
						} = await doAdd(sendObj);
						this.$u.toast(msg);
						if (code != 1) return;
					}
				}
				setTimeout(_ => {
					// this.refreshBeforePageData();
					uni.$emit('refreshData');
					uni.navigateBack();
				}, 500);
			}
		}
	};
</script>

<style lang="scss">
	.sub-table-main {
		min-height: 388rpx;
	}

	.line {
		height: 10rpx;
		background-color: #dddddd;
	}

	.title-box {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.sub-table-title {
			font-size: 30rpx;
		}
	}

	.sub-table-cont {
		min-height: 60rpx;

		.row-box {
			display: flex;
			justify-content: space-between;
			padding: 30rpx 0;

			&.cont {
				padding-right: 60rpx;
			}

			.text {
				margin: 0 10rpx;
			}
		}

		.name {
			margin-right: 10rpx;
		}

		.content {
			display: flex;
			flex-wrap: wrap;

			.text {
				width: 50%;
				padding: 30rpx 0;
			}
		}
	}

	.popup-main {
		width: 600rpx;

		.popup-title {
			font-size: 30rpx;
			text-align: center;
			line-height: 2;
			padding: 10rpx 0;
		}
	}
</style>
